package com.andova.toolkit.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.LayoutRes;

/**
 * Created by Administrator on 2017-07-07.
 *
 * @author kzaxil
 * @since 1.0.0
 */
public abstract class BaseAdapter<T> extends android.widget.BaseAdapter {
    private List<T> mList = new ArrayList<>();
    private List<ViewHolder> mHolderList = new ArrayList<>();

    public void add(T model) {
        if (model == null) return;
        mList.add(model);
    }

    public void add(List<T> list) {
        if (list == null || list.size() == 0) return;
        mList.addAll(list);
    }

    public void list(List<T> list) {
        if (list == null || list.size() == 0) return;
        mList = list;
    }

    public void remove(T model) {
        mList.remove(model);
    }

    public List<T> list() {
        return mList;
    }

    public void clear() {
        mList.clear();
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        if (convertView == null) {
            vh = new ViewHolder(parent.getContext(), layout(), parent);
            convertView = vh.itemView;
            convertView.setTag(vh);
            mHolderList.add(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }
        try {
            execute(vh.itemView, position, mList.get(position));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return convertView;
    }

    public List<ViewHolder> viewHolderList() {
        return mHolderList;
    }

    @LayoutRes
    public abstract int layout();

    public abstract void execute(View itemView, int position, T model);

    public static class ViewHolder {
        public View itemView;

        ViewHolder(Context context, @LayoutRes int resLayout, ViewGroup parent) {
            itemView = LayoutInflater.from(context).inflate(resLayout, parent, false);
        }
    }
}
